<?php
header('Content-Type: text/html; charset=utf-8');
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
require_once dirname(__FILE__) . '/../../../libs/phpMailer/class.phpmailer.php';
session_name(SESSION);
session_start();
$myPdo = DbUtils::createPdoInst();
$action = MiscUtils::getParam('action', '');
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'save':
      save($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo $e->getMessage();
}

function save($myPdo) {
  if (!isset($_SESSION['index' . USER])) {
    return;
  }
  $to = MiscUtils::getParam('to', '');
  $account = MiscUtils::getParam('account', '');
  $first_name = MiscUtils::getParam('first_name', '');
  $last_name = MiscUtils::getParam('last_name', '');
  $phone = MiscUtils::getParam('phone', '');
  
  unset($_SESSION['account']);
  unset($_SESSION['first_name']);
  unset($_SESSION['last_name']);
  unset($_SESSION['phone']);
  unset($_SESSION['account_err']);
  unset($_SESSION['first_name_err']);
  unset($_SESSION['last_name_err']);
  unset($_SESSION['phone_err']);
  
  $is_err = 0;
  if (!filter_var($account, FILTER_VALIDATE_EMAIL)) {
    $_SESSION['account_err'] = 'Not a proper email';
    $is_err = 1;
  } else {
    if ($account != $_SESSION['index' . USER]->account) {
      $cond_vals = new stdClass();
      $cond_vals->c = 't.account = :v1';
      $cond_vals->v = array(':v1' => $account);
      $tmp = DbUtils::get($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
      if (count($tmp) > 0) {
        $_SESSION['account_err'] = 'Email has been used';
        $is_err = 1;
      }
    }
  }
  
  if ($first_name == '') {
    $_SESSION['first_name_err'] = 'Can not be empty';
    $is_err = 1;
  }
  
  if ($last_name == '') {
    $_SESSION['last_name_err'] = 'Can not be empty';
    $is_err = 1;
  }
  
  if ($phone == '') {
    $_SESSION['phone_err'] = 'Can not be empty';
    $is_err = 1;
  }
  
  if ($is_err == 1) {
    $_SESSION['account'] = $account;
    $_SESSION['first_name'] = $first_name;
    $_SESSION['last_name'] = $last_name;
    $_SESSION['phone'] = $phone;
  } else {
    $_SESSION['index' . USER]->account = $account;
    $_SESSION['index' . USER]->first_name = $first_name;
    $_SESSION['index' . USER]->last_name = $last_name;
    $_SESSION['index' . USER]->phone = $phone;
    DbUtils::update($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_customer', $_SESSION['index' . USER]);
  }
  
  echo "
  <script>
  location.href = '$to';
  </script>
  ";
  return;
}
?>
